package com.st.warehouse.utils;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;


import com.st.warehouse.bean.SpinnerItem;

import java.util.List;

public class SpinnerUtils {

    public static void setupSpinner(Context context, Spinner spinner, List<String> items, final SpinnerListener listener) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, items);
        spinner.setAdapter(adapter);

        // 设置下拉框选择监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                if (listener != null) {
                    listener.onItemSelected(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // Do nothing here
            }
        });
    }

    /**
     * 自定义key-value数据下拉
     * @param context
     * @param spinner
     * @param items
     * @param listener
     */
    public static void setupSpinner2(Context context, Spinner spinner, List<SpinnerItem> items, final SpinnerListener listener) {
        ArrayAdapter<SpinnerItem> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        int width = spinner.getMeasuredWidth();
        spinner.setMinimumWidth(Math.min(width, 300));// 设置最大宽度
        // 设置下拉框选择监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                if (listener != null) {
                    listener.onItemSelected(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // Do nothing here
            }
        });
    }
    public interface SpinnerListener {
        void onItemSelected(int position);
    }
}
